import requests
from lxml import etree

url = 'http://www.66ip.cn/3.html'
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36'
}
with open('ip.txt', 'w', encoding='utf-8') as f:
    for i in range(1, 10):
        url = 'http://www.66ip.cn/{i}.html'
        # 发送请求
        resp = requests.get(url, headers=headers)
        # 设置编码
        resp.encoding = 'gbk'
        # 接收响应
        # 创建可以提取数据的对象
        e = etree.HTML(resp.text)
        # 提取ip
        ips = e.xpath('//div[1]/table/tr/td[1]/text()')
        # 提取端口
        ports = e.xpath('//div[1]/table/tr/td[2]/text()')
        # 提取地址
        address = e.xpath('//div[1]/table/tr/td[3]/text()')
        # 保存文本
        for i, p, a in zip(ips, ports, address):
            f.write(f'IP 地址:{i}--端口号:{p}--地址:{a}\n')
